package me.chan.chatting.server.serialize;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
public enum SerializeAlgo implements Serializer {

    JDK(0) {

        @Override
        public <T> byte[] serialize (T t) throws IOException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(t);
            return bos.toByteArray();
        }

        @Override
        public <T> T deserialize(Class < T > clazz, byte[] bytes) throws IOException {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream oos = new ObjectInputStream(bis);
            T t = null;
            try {
               t = (T) oos.readObject();
            } catch (ClassNotFoundException e) {
                log.error("{}", e);
            }
            return t;
        }
    },

    JSON(1) {
        @Override
        public <T> byte[] serialize(T t) throws IOException {
            Gson gson = new Gson();
            String json = gson.toJson(t);
            return json.getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public <T> T deserialize(Class<T> clazz, byte[] bytes) throws IOException {
            Gson gson = new Gson();
            return gson.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
        }

    },

    HESSIAN(2) {
        @Override
        public <T> byte[] serialize(T t) throws IOException {
            return new byte[0];
        }

        @Override
        public <T> T deserialize(Class<T> clazz, byte[] bytes) throws IOException {
            return null;
        }
    };

    SerializeAlgo(int serial) {
        this.serial = serial;
    }

    private int serial;

    public int getSerial() {
        return this.serial;
    }


    public static void main(String[] args) {
        System.out.println(SerializeAlgo.valueOf("JSON") == SerializeAlgo.JSON);
    }
}
